package simple;

import data.TreeNode;

import java.util.Stack;

/**
 * @author cmqzyd0700@163.com
 * @version 1.0
 * @since 2020/5/17 23:17
 */
public class No101_对称二叉树 {
    public static void main(String[] args) {
        TreeNode data = new TreeNode(1);
        data.left = new TreeNode(2);
        data.right = new TreeNode(2);
        data.left.left = new TreeNode(3);
        data.left.right = new TreeNode(4);
        data.right.left = new TreeNode(4);
        data.right.right = new TreeNode(3);

        Solution101 solution101 = new Solution101();
        boolean symmetric = solution101.isSymmetric(data);
        System.out.println(symmetric);

    }
}

class Solution101 {
    public boolean isSymmetric(TreeNode root) {
        if (root == null) {
            return true;
        }
        //stack
        //定义栈,放树
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root.right);
        stack.push(root.left);

        while (!stack.isEmpty()) {
            TreeNode leftTree = stack.pop();
            TreeNode rightTree = stack.pop();

            if (leftTree == null && rightTree == null) {
                continue;
            }
            //说明有一个为null
            if (leftTree == null || rightTree == null) {
                return false;
            }
            //必然两个子树都不是null
            if (leftTree.val != rightTree.val) {
                return false;
            } else {
                stack.push(rightTree.left);
                stack.push(leftTree.right);
                stack.push(rightTree.right);
                stack.push(leftTree.left);
            }
        }
        return true;
    }
}


    //public boolean isSymmetric(TreeNode root) {
    //    if (root == null) {
    //        return true;
    //    }
    //    return isSymmetric(root.left, root.right);
    //}
    //
    //
    ////leftTree:root的左子树
    ////rightTree:root的右子树
    //public boolean isSymmetric(TreeNode leftTree, TreeNode rightTree) {
    //    if (leftTree == null && rightTree == null) {
    //        return true;
    //    }
    //    if (leftTree == null || rightTree == null) {
    //        return false;
    //    }
    //    boolean flag = true;
    //    if (leftTree.val == rightTree.val) {
    //        return flag && isSymmetric(leftTree.left, rightTree.right)
    //                && isSymmetric(leftTree.right, rightTree.left);
    //    }
    //    return false;
    //}